package com.example.boot_demo.dao.jdbctemplate;

import com.example.boot_demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<User> queryUsers() {
        // 查询所有用户
        String sql = "select * from t_user";
        return jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(User.class));
    }

    public User getUser(Long id) {
        // 根据主键ID查询
        String sql = "select * from t_user where id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
    }

    public int delUser(Long id) {
        // 根据主键ID删除用户信息
        String sql = "DELETE FROM t_user WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    public int addUser(User user) {
        // 添加用户
        String sql = "insert into t_user(name, address) values(?, ?)";
        return jdbcTemplate.update(sql, user.getName(), user.getAddress());
    }


    public int editUser(Long id,User user) {
        // 根据主键ID修改用户信息
        String sql = "UPDATE t_user SET name = ? ,address = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getName(), user.getAddress(), id);
    }


}
